<template>
  <div>
    <el-dialog :title="'项目'+propTitle" :visible.sync="visible" :modal-append-to-body="true" :append-to-body="true" width="700px">
      <!-- {{JSON.stringify(propFormData)}} -->
      <el-form ref="form" :model="propFormData" :rules="formRules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="propFormData.projectName" placeholder="请填写项目名称" :disabled="isDisabled || this.propTitle=='修改'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="projectType">
              <el-select v-model="propFormData.projectType" placeholder="请选择当前类型" clearable :disabled="isDisabled" style="width:100%">
                <el-option v-for="(item,index) in propDictData.projectType" :key="index" :label="item.dictLabel" :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售员" prop="salemanId">
              <el-select v-model="propFormData.salemanId" placeholder="请选择销售员" clearable :disabled="isDisabled" style="width:100%" @change="salemanChangeFn">
                <el-option v-for="(item,index) in salesmanList" :key="index" :label="item.nickName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="principalId">
              <el-select v-model="propFormData.principalId" placeholder="请选择项目负责人" clearable :disabled="isDisabled" style="width:100%" @change="principalChangeFn">
                <el-option v-for="(item,index) in PMList" :key="index" :label="item.nickName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属地" prop="projectLocation">
              <el-input v-model="propFormData.projectLocation" placeholder="请填写归属地" :disabled="isDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同金额(万)" prop="projectAmount">
              <el-input v-model="propFormData.projectAmount" type="number" :step="0.1" :min="0" placeholder="请填写项目金额(万)" :disabled="isDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="净合同额(万)" prop="netContractAmount">
              <el-input v-model="propFormData.netContractAmount" type="number" :step="0.1" :min="0" placeholder="请填写净合同额(万)" :disabled="isDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目状态" prop="projectStatus">
              <el-select v-model="propFormData.projectStatus" placeholder="请选择当前状态" clearable :disabled="isDisabled" style="width:100%">
                <el-option v-for="(item,index) in propDictData.projectStatus" :key="index" :label="item.dictLabel" :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否立项" prop="approval">
              <el-select v-model="propFormData.approval" placeholder="请选择是否立项" clearable :disabled="isDisabled" style="width:100%">
                <el-option v-for="(item,index) in propDictData.approval" :key="index" :label="item.dictLabel" :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计启动时间" prop="planStartTime">
              <el-date-picker style="width: 100%;" :disabled="isDisabled"
                              v-model="propFormData.planStartTime"
                              type="date"
                              placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计时长(月)" prop="planTime">
              <el-input v-model="propFormData.planTime" type="number" placeholder="请填写预计时长" :disabled="isDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="成员" prop="member">
              <el-select v-model="memberValue" multiple placeholder="请选择成员" clearable :disabled="isDisabled" @change="memberChangeFn" style="width:100%;">
                <el-option v-for="(item,index) in developerList" :key="index" :label="item.nickName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="propFormData.remark" placeholder="请填写备注" :disabled="isDisabled" />
            </el-form-item>
          </el-col>
          <!-- 上传附件 -->
          <el-col :span="24">
            <el-form-item label="上传附件" prop="fileList">
              <el-upload ref="piplineUpload" :headers="piplineHeaders" :action="uploadUrl" :multiple="true" :file-list="propFormData.fileList" :show-file-list="true" :auto-upload="false" :on-success="successUploadFn" :on-remove="uploadRemoveFn" :on-preview="uploadPreviewFn" :disabled="isDisabled">
                <el-button slot="trigger" size="small" type="primary" :disabled="isDisabled">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitPiplineUploadFn" :disabled="isDisabled">上传到服务器</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="box-btn clearfix">
        <el-button type="primary" size="small" v-if="!isDisabled" @click="dialogFormConfirmFn">确定</el-button>
        <el-button size="small" @click="dialogFormCancelFn">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { apiListUser } from '@/api/system/user.js';
  import { apiProjectManageAdd,apiProjectManageUpdate,apiSystemUserListbyrole } from '@/api/pmp/api.pipline.js';
  import { getToken } from '@/utils/auth';

  export default {
    props: {
      propVisible: {
        type: Boolean,
        default: false
      },
      propTitle: {
        type: String,
        default: '新增'
      },
      propFormData: {
        type: Object,
        default: function(){
          return {
            'id': null,
            'projectName': null,
            'salemanName': null,
            'salemanId': null,
            'principalName': null,
            'principalId': null,
            'projectLocation': null,
            'projectType': null,
            'projectAmount': null,
            'netContractAmount': null,
            'planStartTime': null,
            'planTime': null,
            'approval': null,
            'projectFile': null,
            'projectStatus': null,
            'member': [
              /*{"userid":"105","userName":"sales"}*/
            ],
            'remark': null
          };
        }
      },
      propDictData: {
        type: Object,
        default: {
          projectStatus: [],
          projectType: [],
          approval: []
        }
      }
    },
    data (){
      var checkPrincipalId = (rule, value, callback) => {
        if (this.propFormData.approval == 0) {
          if (!value){
            return callback(new Error('请选择项目负责人'));
          }
        }
        return callback();
      };
      return {
        //memberValue: undefined,
        formRules: {
          projectName: [
            { required: true, message: "请填写项目名称", trigger: ['blur'] }
          ],
          salemanId: [
            { required: true, message: "请选择销售员", trigger: ['blur'] }
          ],
          principalId: [
            { validator: checkPrincipalId, trigger: ['blur'] }
          ],
          projectLocation: [
            { required: true, message: "请填写归属地", trigger: ['blur'] }
          ],
          projectType: [
            { required: true, message: "请选择项目类型", trigger: ['blur'] }
          ],
          approval: [
            { required: true, message: "请确认是否立项", trigger: ['blur'] }
          ],
          projectAmount: [
            // { required: true, message: "请填写合同金额", trigger: ['blur'] },
            { pattern: /^([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})$/, message: '合同金额需大于0', trigger: ['blur','change'] }
          ],
          netContractAmount: [
            // { required: true, message: "请填写净合同额", trigger: ['blur'] },
            { pattern: /^([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})$/, message: '净合同额需大于0', trigger: ['blur','change'] }
          ],
          planTime: [
            { pattern: /^([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})$/, message: '时长需大于0', trigger: ['blur','change'] }
          ],
          projectStatus: [
            { required: true, message: "请选择项目状态", trigger: ['blur'] }
          ]
        },
        userList: [],
        salesmanList: [],
        PMList: [],
        developerList: [],
        // 用于把上传结果提交到项目
        fileDataList: [],
        // 临时
        uploadUrl: process.env.VUE_APP_BASE_API + '/inside/recruit/upload',
        piplineHeaders: {
          'Authorization': 'Bearer ' + getToken()
        }
      };
    },
    computed: {
      visible: {
        get (){
          return this.propVisible;
        },
        set (val){
          this.$emit('update:propVisible', val);
          this.$emit('update:propFormData', undefined);
        }
      },
      memberValue: {
        get (){
          var arr = [];
          this.propFormData.member.map((item,index) => {
            arr.push(item.userId);
          });
          return arr;
        },
        set (val){
          console.log('set:',val);
        }
      },
      isDisabled (){
        return this.propTitle=='详情';
      }
    },
    filters: {
      fltMember (data){
        var arr = [];
        data.map((v,i) => {
          arr.push(v.userName);
        });
        return arr.join('，');
      },
    },
    mounted (){
      this.getUserFn();
    },
    watch: {
      propFormData :{
        handler: function (val){
          if(val.projectFile){
            this.propFormData.fileList = JSON.parse(val.projectFile);
          }
        },
        immediate: true
      }
    },
    methods: {
      /* 上传、下载方法集合 */
      successUploadFn (response, file, fileList) {
        this.fileDataList.push({ name: file.name, url: response.url, uid: file.uid });
        console.log('批量上传结果', response, file, fileList, this.fileDataList);
      },
      // 删除上传列表处理
      uploadRemoveFn (v){
        (this.fileDataList || []).splice((this.fileDataList || []).findIndex(item => item.uid === v.uid), 1);
        console.log('uploadRemoveFn', this.fileDataList);
      },
      // 点击下载
      uploadPreviewFn (file){
        let link = document.createElement('a');
        let {url, name} = (this.propFormData.fileList || []).find(item => item.uid === file.uid);

        console.log('uploadPreviewFn', file, url, name);
        //设置下载的文件名
        link.download = name;
        link.style.display = 'none';
        //设置下载路径
        link.href = url;
        //触发点击
        document.body.appendChild(link);
        link.click();
        //移除节点
        document.body.removeChild(link);
      },
      // 上传到服务器
      submitPiplineUploadFn (){
        // 上传之前全部清空，每次上传会重新上传所有内容，后期再考虑删除的问题
        this.$refs.piplineUpload.submit();
      },
      salemanChangeFn (val){
        /*console.log('val:',val);*/
        if(!val){
          this.propFormData.salemanName = '';
          return;
        }
        var o1 = {};
        //o1 = this.userList.find(item => {
        o1 = this.salesmanList.find(item => {
          return item.userId == val;
        });
        this.propFormData.salemanName = o1.nickName;
        console.log('salemanId:',this.propFormData.salemanId,'\nsalemanName:',this.propFormData.salemanName);
      },
      principalChangeFn (val){
        /*console.log('val:',val);*/
        if(!val){
          this.propFormData.principalName = '';
          return;
        }
        var o1 = {};
        o1 = this.PMList.find(item => {
          return item.userId == val;
        });
        this.propFormData.principalName = o1.nickName;
        console.log('principalId:',this.propFormData.principalId,'\nprincipalName:',this.propFormData.principalName);
      },
      memberChangeFn (val){
        /*console.log('val:',val);
        console.log('memberValue:',this.memberValue);*/
        var arr = [];
        this.developerList.map((item,index) => {
          val.map((v,i) => {
            if(item.userId == v){
              arr.push(item);
            }
          });
        });
        this.propFormData.member = arr;
        /*console.log('member:',this.propFormData.member);*/
      },
      //该接口用来做选择人员的时候用
      getUserFn (){
        /*apiListUser()
        .then(res => {
          console.log('res:',res);
          this.userList = res.rows;
        });*/
        apiSystemUserListbyrole({roleKey:'salesman'})
          .then(res => {
            console.log('res:',res);
            this.salesmanList = res.rows;
          });
        apiSystemUserListbyrole({roleKey:'PM'})
          .then(res => {
            console.log('res:',res);
            this.PMList = res.rows;
          });
        //apiSystemUserListbyrole({roleKey:'developer'})
        apiSystemUserListbyrole({roleKey:'all'})
          .then(res => {
            console.log('res:',res);
            this.developerList = res.rows;
          });
      },
      dialogFormCancelFn (){
        this.visible = false;
      },
      dialogFormConfirmFn (){
        var vm = this;
        let propFormData = {...this.propFormData};
        // 处理上传控件参数this.fileDataList
        propFormData.projectFile = JSON.stringify(this.fileDataList);
        console.log('propFormData:',propFormData);
        //alert('先校验，简单校验必填项就好了！');
        this.$refs["form"].validate(valid => {
          if(valid){
            if(this.propTitle=='新增'){
              console.log('调新增接口');
              apiProjectManageAdd(propFormData)
                .then(res => {
                  //console.log('新增成功：',res);
                  this.$message({
                    message: res.msg,
                    type: 'success',
                    duration: 1 * 1000,
                    onClose: function(){
                      vm.visible = false;
                      vm.$parent.getTableDataFn();
                    }
                  });
                },err => {
                  console.log('新增失败：',err);
                });
            }
            else if(this.propTitle=='修改'){
              console.log('调修改接口');
              apiProjectManageUpdate(propFormData)
                .then(res => {
                  //console.log('修改成功：',res);
                  this.$message({
                    message: res.msg,
                    type: 'success',
                    duration: 1 * 1000,
                    onClose: function(){
                      vm.visible = false;
                      vm.$parent.getTableDataFn();
                    }
                  });
                },err => {
                  console.log('修改失败：',err);
                });
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    }
  };
</script>

<style scoped>
  .box-btn{ display: table; margin: 0 auto; padding: 10px 0 5px 0;}
</style>
